package com.cet.programmercarl.algorithmperformancanalysis.链表;

/**
 * @program: algorithm
 * @description: 设计链表
 * @author: 陈恩涛
 * @create: 2022-03-11 16:25
 **/
public class LC707 {


    public static void main(String[] args) {
        MyLinkedList linkedList = new MyLinkedList();
        linkedList.addAtHead(1);
        linkedList.addAtTail(3);
        linkedList.addAtIndex(1,2);   //链表变为1-> 2-> 3
        System.out.println(linkedList.get(1));
        linkedList.deleteAtIndex(1);  //现在链表是1-> 3
        System.out.println(linkedList.get(1));
    }
}

class MyLinkedList{

    private int size;
    private ListNode head;

    public MyLinkedList() {
        head = new ListNode(0);
        size = 0;
    }

    public int get(int index) {
        if (index < 0 || index >= size) {
           return -1;
        }
        ListNode current = head;
        while (index >= 0) {
            current = current.next;
            index--;
        }
        return current.val;
    }

    public void addAtHead(int val) {
        addAtIndex(0, val);
    }

    public void addAtTail(int val) {
        addAtIndex(size, val);
    }

    public void addAtIndex(int index, int val) {

        if (index > size) {
            return;
        }

        if (index < 0) {
            index = 0;
        }

        ListNode pre = head;

        while (index > 0) {
            pre = pre.next;
            index--;
        }
        ListNode insertNode = new ListNode(val);
        insertNode.next = pre.next;
        pre.next = insertNode;
        size++;
    }

    public void deleteAtIndex(int index) {
        if (index < 0 || index >= size) {
            return;
        }

        ListNode pre = head;

        while (index > 0) {
            pre = pre.next;
            index--;
        }

        pre.next = pre.next.next;
        size--;
    }
}


